﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Clandestine.Base;

namespace Clandestine.Graphics
{
    public class RenderThread
    {
        private Thread thread;
        private Graphics graphics;
        private bool renderMustDie; // .Stop() takes this high to indicate render() should exit.
		
		public Func<bool> OverrideRenderFunction;

        private object haha = new object();

        internal RenderThread(Graphics graphics)
        {
            this.thread = new Thread(new ThreadStart(renderThreadProc));
            this.graphics = graphics;
        }

        public bool Started
        {
            get { return (thread.ThreadState == ThreadState.Running || thread.ThreadState == ThreadState.WaitSleepJoin); }
        }

        public void Start()
        {
            // If you try to start twice, we'll throw a hissy fit.
            if (Started)
                throw new Exception("Render thread is already running!");

            renderMustDie = false;
            thread.Start();
        }

        public void Stop()
        {
            // If you try to stop twice, it's not really a big deal.
            if (!Started)
                return;

            renderMustDie = true;

            // Wait for finish.
            lock (haha) { }
        }

        private void renderThreadProc()
        {
            lock (haha)
            {
                while (!renderMustDie)
                {
					if (OverrideRenderFunction == null || (OverrideRenderFunction() == false))
                    	graphics.Render();
                    Thread.Sleep(25);
                }
            }
        }
    }
}
